﻿using System;
using System.Windows;
using dotNetMagazin201108.PresentationLayer.Views;
using dotNetMagazin201108.BusinessLayer;
using System.Threading;

namespace dotNetMagazin201108.PresentationLayer.Presenter
{
    public class CompanyFormPresenter
    {
        public CompanyFormView View;
        public event EventHandler<EventArgs> CompanyCreated;
        public Company NewCompany { get; private set; }

        public CompanyFormPresenter(CompanyFormView view)
        {
            View = view;
            View.Dispatcher.BeginInvoke(delegate() {
                View.Cancel.Click += new RoutedEventHandler(Cancel_Click);
                View.Apply.Click += new RoutedEventHandler(Apply_Click);
            });
        }

        private void Apply_Click(object sender, RoutedEventArgs e)
        {
            Company company = new Company() { Id = 0, Name = View.CompanyName.Text, Size = int.Parse(View.CompanySize.Text.Trim()) };
            Thread t = new Thread(delegate()
            {
                CompanyRepository companies = Factory.CreateCompanyRepository();
                companies.Add(company);

                NewCompany = company;

                View.Dispatcher.BeginInvoke(delegate() {
                    View.Close();
                    if (CompanyCreated != null) CompanyCreated(this, EventArgs.Empty);
                });
            });
            t.Start();
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            View.Close();
        }

        public void ShowView()
        {
            View.CompanyName.Text = string.Empty;
            View.CompanySize.Text = string.Empty;
            View.Show();
        }
    }
}
